package com.woyou.activity;

import java.util.Timer;
import java.util.TimerTask;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.jing.biandang.R;
import com.umeng.analytics.MobclickAgent;
import com.woyou.bean.FmInfo;
import com.woyou.component.ActionbarView;
import com.woyou.component.LoadingView;
import com.woyou.component.MenuView;
import com.woyou.component.NetHintView;
import com.woyou.component.SuperUI;
import com.woyou.controller.HomeController;
import com.woyou.fragment.order.NewOrderFragment;
import com.woyou.fragment.order.OrderFragment;
import com.woyou.fragment.shop.ShopFragment;
import com.woyou.model.GoodsManagerModel;
import com.woyou.model.OrderManageModel;
import com.woyou.service.MessageConnection;
import com.woyou.service.Observer;
import com.woyou.utils.NavigationbarUtils;
import com.woyou.utils.SoundManager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import net.simonvt.menudrawer.MenuDrawer;

public class HomeActivity extends SherlockFragmentActivity implements Observer,IHomeMaster {
	public MenuDrawer menuDrawer;
	private ActionBar actionBar;
	/**
	 * 自定义的ActionbarView
	 */
	public ActionbarView actionbarView;
	/**
	 *  左边店铺信息菜单
	 */
	public MenuView menuView;
	/**
	 *  右边内容区
	 */
	private View contentView;
	/**
	 * 加载loading
	 */
	public LoadingView loadingView;
	/**
	 * 网络提示
	 */
	public NetHintView netHintView;
	// 碎片类
	private FragmentManager fm;
	/**
	 * 观察者对象
	 */
	private MessageConnection mc;
	/**
	 * 外卖机超过5分钟未做任何操作执行相应的任务
	 */
	private Timer backOrderTimer = null;
	private TimerTask backOrderTimerTask = null;
	/**
	 * 判断外卖机超过5分钟未做任何操作执行相应的任务是否可以切换 true 能跳转，false 不能跳转
	 */
	public boolean isCanSwitchView = true;

	/**
	 * 保持解锁5分钟的标志位
	 */
	public boolean isUnlock5Minute = false;
	/**
	 * 连续点击两次鼠标右键退出,记录第一次点击返回的时间
	 */
	private long firstTime = 0;
	/**
	 * 标志是否可以修改店铺信息
	 */
	public boolean isCanShopSetting = false;
	/**
	 * HomeController
	 */
	public HomeController homeController;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		menuDrawer = MenuDrawer.attach(this, MenuDrawer.Type.OVERLAY);
		menuDrawer.setMenuSize(500);
		menuDrawer.setDropShadowEnabled(false);
		fm = getSupportFragmentManager();
		// 初始化actionbar
		initActionBar();
		// 初始化左菜单
		initMenuView();
		// 初始化内容区域
		initContentView();
		// 初始化基本数据
		menuView.init();
		// 初始化声音管理器
		SoundManager.getInstance(this);
		// 启动Socket心跳并且注册观察者监听器
		mc = MessageConnection.getInstance();
		mc.startHeartBeatThreads(this);
		mc.registerObserver(this);
		// 同步服务器时间
		actionbarView.syncServerTime();
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	/**
	 * 初始化ActionBar
	 */
	public void initActionBar() {
		actionBar = getSupportActionBar();
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setDisplayShowHomeEnabled(false);
		ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
		actionbarView=new ActionbarView(this,menuDrawer);
		actionBar.setCustomView(actionbarView, layout);
	}

	/**
	 * 初始化左边菜单
	 */
	public void initMenuView() {
		// 左边菜单的抽屉
		menuView=new MenuView(this,fm,menuDrawer,actionbarView);
		menuDrawer.setMenuView(menuView);
		actionbarView.setMenuView(menuView);
	}

	/**
	 * 初始化右边内容区
	 */
	public void initContentView() {
		homeController=new HomeController(this, fm, menuDrawer,actionbarView);
		// 显示OrderFragment
		openFM(new FmInfo(OrderFragment.class, null,false));
		contentView = View.inflate(this,R.layout.layout_home, null);
		menuDrawer.setContentView(contentView);
		//加载loading
		loadingView=(LoadingView)contentView.findViewById(R.id.home_loading);
		// 断网提示
		netHintView=(NetHintView)contentView.findViewById(R.id.home_nethintview);
		netHintView.setParams(this);
	}

	/**
	 * 接收推送信息
	 */
	@Override
	public void update(final int type, final String orderNum) {

		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				switch (type) {
				case 1:
					homeController.handleNewOrder(actionbarView);
					break;
				case 2:
					homeController.handleCancleOrder(orderNum);
					break;
				}
			}
		});
	}

	@Override
	protected void onStart() {
		super.onStart();
		NavigationbarUtils.getInstance(this).hide();
	}

	/**
	 * 监听全局的ACTION_DOWN事件，如果外卖机超过5分钟未做任何操作 如果未送订单>0，界面自动回到营业订单/未送订单
	 * 如果未送订单=0，界面自动回到营业订单/已送订单
	 * 
	 * @param ev
	 * @return
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// 拦截全局的ACTION_DOWN事件
		if (MotionEvent.ACTION_DOWN == ev.getAction()) {
			if (backOrderTimer != null) {
				backOrderTimer.cancel();
				backOrderTimer = null;
			}
			if (backOrderTimerTask != null) {
				backOrderTimerTask.cancel();
				backOrderTimerTask = null;
			}
			backOrderTimer = new Timer();
			backOrderTimerTask = new TimerTask() {
				@Override
				public void run() {
					// 判断当前的显示的碎片如果是新订单或者是取消订单就绕过
					if (!isCanSwitchView) {
						return;
					}
					runOnUiThread(new Runnable() {
						public void run() {
							/**
							 * 判断当前是否有未送订单
							 */
							if (getOrderFm().waitPersonView.wait4Num >= 1) {
								homeController.returnOrderFragment(true,menuView);
							} else {
								homeController.returnOrderFragment(false,menuView);
							}
						}
					});
				}
			};
			backOrderTimer.schedule(backOrderTimerTask, 5 * 60 * 1000, 5 * 60 * 1000);
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	protected void onDestroy() {
		OrderManageModel.getInstance().clearAllData();
		GoodsManagerModel.getInstance().clearAllData();
		homeController.clearFragmentList();
		super.onDestroy();
		actionbarView.onDestroy();
	}

	/**
	 * 监听返回按钮
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long secondTime = System.currentTimeMillis();
			if (secondTime - firstTime > 2000) {
				// 如果两次按键时间间隔大于2秒，则不退出
				SuperUI.openToast(this, "再按一次退出");
				firstTime = secondTime;// 更新firstTime
				return true;
			} else {
				// 两次按键小于2秒时，退出应用
				finish();
				System.exit(0);
			}
		}
		return false;
	}

	@Override
	public void openSubFM(Fragment beforeFm,FmInfo fmInfo) {
		homeController.openSubFM(beforeFm,fmInfo);
	}

	@Override
	public void openFM(FmInfo fmInfo) {
		homeController.openFM(fmInfo);
	}

	@Override
	public void hideInputMethod() {
		homeController.hideInputMethod();
	}

	@Override
	public void showLoadingHint() {
		loadingView.showLoadingHint();
	}

	@Override
	public void hideLoadingHint() {
		loadingView.hideLoadingHint();
	}

	@Override
	public NewOrderFragment getNewOrderFm() {
		return homeController.getNewOrderFm();
	}

	@Override
	public OrderFragment getOrderFm() {
		return homeController.getOrderFm();
	}

	@Override
	public ShopFragment getShopFm() {
		return homeController.getShopFm();
	}

	@Override
	public void backBeforeFM() {
		homeController.backBeforeFM();
	}

	@Override
	public void modifyActionBar(Fragment fragment, String name) {
		homeController.modifyActionBar(fragment, name);
	}

	@Override
	public void resetActionBar(boolean isClear) {
		homeController.resetActionBar(isClear);
	}

	@Override
	public Fragment getCurrentFragment() {
		return homeController.getCurrentFragment();
	}

	@Override
	public void checkBossPW() {
		homeController.checkBossPW();
	}

}